package com.jiaz.web;

import com.jiaz.untils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author jiajiazi
 * @version 1.0
 * @date 2022/4/24 13:14
 */

public class HttpInterceptor implements HandlerInterceptor {

    private static final String START_TIME = "requestStartTime";
    private Logger logger = LoggerFactory.getLogger(HttpInterceptor.class);

    /**
     * 拦截请求url和请求参数
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        RequestBodyWrapper requestBodyWrapper = new RequestBodyWrapper(request);
        String url = requestBodyWrapper.getRequestURI();
        Map<String, String[]> parameterMap = requestBodyWrapper.getParameterMap();
        String bodyParam = requestBodyWrapper.getBody();
        long start = System.currentTimeMillis();
        logger.info("request start | url : [{}], params : [{}], bodyParam : [{}]", url, JsonUtils.toJson(parameterMap), bodyParam);
        request.setAttribute(START_TIME, start);
        return true;
    }

    /**
     * 请求结束后，计算url花费时间，响应时间超过5秒邮件提醒
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String url = request.getRequestURL().toString();
        long start = (long) request.getAttribute(START_TIME);
        long end = System.currentTimeMillis();
        long costTime = end - start;
        logger.info(" request finished | url : [{}], costTime : [{}] ms ", url, costTime);
        if (costTime / 1000 > 5) {
            logger.info("request finished | url : [{}], 请求时间 : [{}] s ", url, costTime / 1000);
            /*MailSender ms = new MailSender(null, null, SystemConstant.MIER_DEVELOPER_EMAIL, null, null,
                    "接口响应超时三秒提醒", DateUtil.getFormatTime(new Date()) + "," + SessionUtil.getUsername()
                    + ", request url : " +  url  + ", request time : " + costTime/1000 + " s ");
            ms.start();*/
        }
    }

}
